import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

import '../theme/custom_color.dart';

class LoadableIconButton extends HookWidget {
  final Widget icon;
  final Future<void> Function() onPressed;

  const LoadableIconButton({
    Key? key,
    required this.icon,
    required this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var loadingState = useState(false);
    var successState = useState(false);
    buildIcon() {
      if (successState.value) {
        return Icon(
          Icons.check_circle,
          color: Theme.of(context).extension<CustomColors>()!.success,
        );
      } else if (loadingState.value) {
        return const CircularProgressIndicator();
      } else {
        return icon;
      }
    }

    useEffect(() {
      if (successState.value) {
        Future.delayed(const Duration(seconds: 1), () {
          successState.value = false;
        });
      }
      return null;
    }, [successState.value]);

    return IconButton(
      onPressed: () async {
        loadingState.value = true;
        try {
          await onPressed();
          successState.value = true;
        } finally {
          loadingState.value = false;
        }
      },
      icon: buildIcon(),
    );
  }
}
